package com.leisai.manager.controller.system;

import com.alibaba.fastjson.JSONArray;
import com.leisai.manager.common.utils.DateUtils;
import com.leisai.manager.common.utils.StringUtil;
import com.leisai.manager.dao.ReportMapper;
import com.leisai.manager.dto.ReportDTO;
import com.leisai.manager.dto.WriteDTO;
import com.leisai.manager.pojo.BaseAdminUser;
import com.leisai.manager.pojo.Report;
import com.leisai.manager.pojo.Temp;
import com.leisai.manager.pojo.Write;
import com.leisai.manager.service.ReportService;
import com.leisai.manager.service.TempService;
import com.leisai.manager.service.WriteService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.leisai.manager.common.utils.IndutryConfigUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: jim
 * @Date: 2021/12/02/15:49
 * @Description:
 */
@Controller
@RequestMapping("write")
public class WriteController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    WriteService writeService;
    @Autowired
    TempService tempService;
    @Autowired
    ReportService reportService;

    /**
     *
     * 功能描述: 跳到填写界面
     *
     * @param:
     * @return:
     * @auther: jim
     * @date: 2021-11-23
     */
    @RequestMapping("writePage")
    public String writePage(ReportDTO reportDTO , Model model) {
        logger.info("进入填写界面");
        model.addAttribute("report",reportDTO);
        Temp temp = tempService.getTempById(reportDTO.getTempId().longValue());
        model.addAttribute("temp",temp);
        List<WriteDTO> writes = writeService.getWrite(reportDTO.getReportId());
        model.addAttribute("writes",writes);
        return "write/writePage";
    }

    /**
     *
     * 功能描述: 打开销售数据弹窗
     *
     * @param:
     * @return:
     * @auther: jim
     * @date: 2021-11-23
     */
    @RequestMapping("saledata")
    public String saleData(ReportDTO reportDTO , Model model) {
        logger.info("加载销售数据");
        Map<String, Object> element = IndutryConfigUtils.getElement("product-detail");
        Long tempId = Long.parseLong(element.get("key")+"");
        reportDTO.setTempId(tempId.intValue());
        ReportDTO report = reportService.getReportByObject(reportDTO);
        model.addAttribute("report",report);
        Temp temp = tempService.getTempById( tempId );
        model.addAttribute("temp",temp);
        List<WriteDTO> writes = writeService.getWrite(report.getReportId());
        model.addAttribute("writes",writes);
        return "write/saleData";
    }

    /**
     *
     * 功能描述:设置模板[新增或更新]
     *
     * @param:
     * @return:
     * @auther: jim
     * @date: 2021/12/01 9:42
     */
    @PostMapping("setWrite")
    @ResponseBody
    public Map<String,Object> setWrite(@RequestParam(value="list",required=false) String str) {
        logger.info("填写报表[新增或更新]！" );
        List<Write> writes = new ArrayList<Write>(JSONArray.parseArray(str, Write.class));
        Map<String,Object> data = new HashMap();
        //更新report
        Report report = reportService.getReportById(writes.get(0).getReportId());
        Integer tempId = report.getTempId();
        report.setReportId(writes.get(0).getReportId());
        report.setStatus(1);
        report.setWriteTime(DateUtils.getCurrentDate());
        //获取当前登陆的用户信息
        BaseAdminUser user = (BaseAdminUser) SecurityUtils.getSubject().getPrincipal();
        report.setUserId(user.getId());
        List<WriteDTO> write = writeService.getWrite(writes.get(0).getReportId());
        Map<String, Object> resultMap = reportService.updateReport(report);
        Map<String ,Object> map = new HashMap<>();
        if(Integer.parseInt(resultMap.get("code")+"")==1){
            if(writes.get(0).getWriteId() == null ){
                //新填写
                data = writeService.addWrite(writes);
                map.put("code",1);
                map.put("msg","填写成功");
                logger.info("报表填写成功");
            }else{
                //修改
                data = writeService.updateWrite(writes);
                map.put("code",1);
                map.put("msg","报表修改成功");
                logger.info("报表修改成功");
            }
            map.put("code",0);
            map.put("msg","报表填写失败");
            logger.error("填写失败");
        }else {
            map.put("code",0);
            map.put("msg","报表填写失败");
            logger.error("填写失败");
        }
        //只针对业绩分析-产品打开模板进行合计
        Map<String, Object> element = IndutryConfigUtils.getElement("product-detail");
        if (element.get("key").equals(tempId+"")) {
            Map<String, Object> msgMap = writeService.calculateTotal(report.getReportId());
            if (msgMap.get("code").equals(0)) {
                data.put("code", msgMap.get("code"));
                data.put("msg", msgMap.get("msg"));
            }
        }
        return data;
    }

    /**
     * 功能描述：获得填写内容
     * @param reportId
     * @return
     */
    @PostMapping("getWrites")
    @ResponseBody
    public List<WriteDTO> getWrites(Integer reportId){
        List<WriteDTO> writes = null;
        try {
            writes = writeService.getWrite(reportId );
            if (writes == null){
                logger.error("该报表内容查询为空！");
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询失败！");
        }
        logger.error("查询报表id："+reportId+"数据长度:"+writes.size());
        return  writes;
    }
}
